package com.getguang.superstore.cell

import android.graphics.drawable.ColorDrawable
import androidx.appcompat.app.AppCompatActivity
import com.getguang.superstore.databinding.CellDealsItemBinding
import com.getguang.superstore.dialog.CouponCodeCopyDF
import com.getguang.superstore.home.SSDealHomeActivity
import com.guadou.lib_baselib.view.span.dsl.buildSpannableString
import com.starblink.android.basic.adapter.BaseBindingVH
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.ext.color
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.toThousDigitsStr
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.sensorsdata.extension.trackBizSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.util.FontUtil
import com.starblink.basic.ext.load
import com.starblink.rocketreserver.fragment.MerchantWebVOF
import org.joda.time.DateTime
import java.util.Locale

/**
 *  Create by yuanl at 2023/10/12
 **/
class DealsItemCell(
    binding: CellDealsItemBinding,
) :
    BaseBindingVH<MerchantWebVOF, CellDealsItemBinding>(binding) {

    override fun onBind(model: MerchantWebVOF, position: Int) {
        binding.tvStoreName.text = model.merchantName
        binding.tvDes.text = model.getMerchantShowDes()

        binding.tvDiscount.visibleOrGone(model.merchantDiscountInfo != null) {
            //text = "Up to ${model.discount}% off"
            buildSpannableString {
                addText((model.merchantDiscountInfo?.prefix?.let {
                    if (it.endsWith(" ")) {
                        it
                    } else {
                        "$it "
                    }
                } ?: "")) {
                    //typeface = FontUtil.getTypeface(FontUtil.DM_SANS_MEDIUM)
                }
                addText(model.merchantDiscountInfo?.discount ?: "") {
                    val t = FontUtil.getTypeface(FontUtil.DM_SANS_BOLD)
                    if (t != null) {
                        this.setTypeface(t)
                    }
                }
                addText(model.merchantDiscountInfo?.suffix?.let {
                    if (it.startsWith(" ")) {
                        it
                    } else {
                        " $it"
                    }
                } ?: "") {
                    //typeface = FontUtil.getTypeface(FontUtil.DM_SANS_MEDIUM)
                }
            }
        }


        binding.img.load(
            model.imageUrl,
            placeholder = ColorDrawable(color(com.starblink.basic.style.R.color.gu_yellow_100))
        )
        binding.imgLogo.load(model.logo, model.merchantName)

        binding.tvViews.visibleOrGone((model.currentPv ?: 0) > 0) {
            text = "${model.currentPv!!.toThousDigitsStr()} Viewing"
        }

        val showCoupon = model.hasCouponCode == true && model.couponCode?.isNotEmpty() == true
        if (showCoupon) {
            binding.btn.text = "Get Code"
            binding.layoutCode.visible()
            binding.tvCode.text = model.couponCode
        } else {
            binding.btn.text = "Shop Now"
            binding.layoutCode.gone()
        }

        binding.tvValidTime.visibleOrGone(model.endTime != null) {
            binding.tvValidTime.text = kotlin.runCatching {
                val dateStr = DateTime(model.endTime).toString("dd/MMM/yyyy", Locale.ENGLISH)
                "Valid until: $dateStr"
            }.getOrNull()
        }
        binding.btn.setOnClickListener {
            itemView.performClick()
        }

        itemView.setOnClickListener {
            if (showCoupon) {
                showCouponDialog(model)
            } else {
                toStorePage(model)
            }
        }

        itemView.trackData(
            findParentPageSpmId(),
            SpmElementDef.StoreIcon_33032,
            params = mutableMapOf<String, String>().apply {
                findParentPageSpmParams()?.takeIf { it.isNotEmpty() }?.let {
                    putAll(it)
                }
                putAll(
                    mapOf(
                        "merchantName" to model.merchantName.orEmpty(),
                        "index" to getTrackIndex().toString(),
                        "isCode" to (if (showCoupon) 1 else 0).toString(),
                    )
                )
            },
            businessSuffixID = model.trackBizSuffixId(),
        )

    }

    private fun getTrackIndex() =
        if (itemView.context is SSDealHomeActivity) bindingAdapterPosition - 1 else bindingAdapterPosition

    private fun toStorePage(model: MerchantWebVOF) {
        CommonRoute.startStoreLinkWithCode(
            model.merchantWebNo,
            model.merchantWebUrl,
            model.couponCode ?: "",
            model.merchantDiscountInfo
        )
    }

    private fun showCouponDialog(model: MerchantWebVOF) {
        (itemView.context as? AppCompatActivity)?.supportFragmentManager?.let {
            CouponCodeCopyDF.show(
                it, model.couponCode ?: "",
                model.getMerchantShowDes(),
                model.merchantWebUrl, getTrackIndex(),
                model.merchantName, model.merchantWebNo,model.merchantDiscountInfo
            )
        }
    }

    private fun MerchantWebVOF.getMerchantShowDes() =
        merchantDesc.orEmpty().ifEmpty { "Check the store out for more surprising discounts! " }

}